<template>
  <div>
    <a-space class="mb-20">
      <a-button type="primary" @click="handleAdd">添加</a-button>
    </a-space>
    <tablePage
      ref="tablePageRef"
      :columns="columns"
      :methods="sortMethods"
      :api="getShopAddress"
      :bordered="true"
      @delete="handleDelete"
      @update="handleEdit"
    />

    <!-- 添加modal -->
    <a-modal
      v-model:visible="storeAddressData.enableAddModal"
      :align-center="false"
      :footer="false"
      :width="680"
    >
      <template #title> {{ storeAddressData.enableAddTitle }} </template>
      <a-form
        ref="formRef"
        :model="storeAddressData.form"
        @submit="handleAddOk"
      >
        <a-form-item
          field="addressName"
          label="自提点名称"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="storeAddressData.form.addressName" />
        </a-form-item>
        <a-form-item
          field="mobile"
          label="联系电话"
          :rules="[MOBILE, REQUIRED]"
          :validate-trigger="['change']"
          validate-phone
        >
          <a-input v-model="storeAddressData.form.mobile" :max-length="11">
            <template #prepend> +86 </template>
          </a-input>
        </a-form-item>
        <a-form-item
          field="address"
          label="地址"
          :rules="[REQUIRED, VARCHAR255]"
        >
          <div>
            <city
              :key="isShowCity"
              :ids="storeAddressData.form.addressId"
              :address="storeAddressData.form.address"
              @callback="cityRes"
            />
          </div>
        </a-form-item>
        <a-form-item
            field="addressDetail"
            label=详细地址
            :rules="[REQUIRED, VARCHAR255]"
            :validate-trigger="['change']"
        >
          <a-input v-model="storeAddressData.form.addressDetail" />
        </a-form-item>
        <a-form-item label="操作">
          <a-button
            :loading="storeAddressData.formLoading"
            html-type="submit"
            type="primary"
            >保存</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import {
    getShopAddress,
    delShopAddress,
    addShopAddress,
    editShopAddress,
  } from '@/api/shops';
  import { ref, reactive } from 'vue';
  import { MethodsRule } from '@/types/global';
  import { Message } from '@arco-design/web-vue';
  import { VARCHAR255, REQUIRED, VARCHAR20, MOBILE } from '@/utils/validator';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import tablePage from '@/components/table-pages/index.vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import city from '@/components/m-city/index.vue';

  const isShowCity = ref(1);
  const formRef = ref<FormInstance>();
  const aMap = ref(); // 地图坐标ref
  const tablePageRef = ref(); // 表格ref
  interface formInterface {
    enableAddModal: boolean;
    enableAddTitle: string;
    formLoading: boolean;
    fid: string | number;
    form: {
      mobile: any;
      address: any;
      addressName: string;
      addressDetail: string;
      center: string;
      longitude: string;
      latitude: string;
      id?: string;
      addressId: any;
      [key: string]: any;
    };
    [key: string]: any;
  }

  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const columns: Array<{ title: string; dataIndex: string }> = [
    {
      title: '自提点名称',
      dataIndex: 'addressName',
    },
    {
      title: '地址',
      dataIndex: 'address',
    },
    {
      title: '详细地址',
      dataIndex: 'addressDetail',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
  ];
  const sortMethods: MethodsRule = {
    title: '操作',
    width: 200,
    methods: [
      {
        title: '修改',
        callback: 'update',
        type: 'text',
        status: 'warning',
      },
      {
        title: '删除',
        callback: 'delete',
        type: 'text',
        status: 'danger',
      },
    ],
  };
  // 数据集
  const storeAddressData = reactive<formInterface>({
    enableAddModal: false,
    enableAddTitle: '添加自提地址',
    formLoading: false,
    fid: '', // 当前form的ids
    form: {
      mobile: '',
      address: '',
      addressName: '',
      center: '',
      longitude: '',
      latitude: '',
      addressId: '',
    }, // 表单提交数据
  });

  // 级联子组件传过来的值
  const cityRes = (val: any) => {
    // storeAddressData.form.addressId = val.ids.filter(i => i && i!== '').join(',');
    // storeAddressData.form.address = val.cities.filter(i => i && i!== '').join(',');
    storeAddressData.form.addressId = val.ids.join(',');
    storeAddressData.form.address = val.cities.join(',');
  };

  // 添加/修改地址
  async function handleAddOk() {
    const auth = await formRef.value?.validate();
    storeAddressData.form.center = '0';
    storeAddressData.form.longitude = '0';
    storeAddressData.form.latitude = '0';
    if (!auth) {
      let res;
      !storeAddressData.fid
        ? (res = await addShopAddress(storeAddressData.form))
        : (res = await editShopAddress(
            storeAddressData.fid,
            storeAddressData.form
          ));

      if (res.data.success) {
        Message.success(`${storeAddressData.fid ? '修改' : '添加'}成功!`);
        storeAddressData.enableAddModal = false;
        tablePageRef.value.init();
      }
    }
  }

  // 点击添加
  function handleAdd() {
    isShowCity.value += 1;
    storeAddressData.enableAddModal = true;
    storeAddressData.fid = '';
    delete storeAddressData.form.id;
    Object.keys(storeAddressData.form).forEach((key) => {
      storeAddressData.form[key] = '';
    });
  }

  // 点击修改地址
  function handleEdit(val: any) {
    isShowCity.value += 1;
    if (val) {
      Object.keys(val.record).forEach((key) => {
        // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
        storeAddressData.form.hasOwnProperty(key)
          ? (storeAddressData.form[key] = val.record[key])
          : '';
      });
      storeAddressData.form.id = val.record.id;
      storeAddressData.fid = val.record.id;
      storeAddressData.enableAddModal = true;
      storeAddressData.enableAddTitle = '修改自提地址';
    }
  }

  // 回调删除
  function handleDelete(data: any) {
    modal.confirm({
      title: '确认删除',
      content: '确认删除自提地址么？',
      alignCenter: false,
      onOk: async () => {
        const res = await delShopAddress(data.record.id);
        if (res.data.success) {
          Message.success('删除成功！');
          tablePageRef.value.init();
        }
      },
    });
  }
</script>

<style scoped lang="less"></style>
